<!--
 * @Author: zhangyang
 * @Date: 2020-12-10 10:51:05
 * @LastEditTime: 2022-05-07 11:55:47
 * @Description: 弹出层组件
-->
<template>
  <NModal
    style="position: fixed; top: 10vh;left: 50%;transform: translateX(-50%);"
    v-bind="$attrs"
    :show="modelValue || showDialog"
    preset="dialog"
    :title="realTitle || title"
    :close-on-esc="false"
    :mask-closable="false"
    :positive-text="sureText"
    :negative-text="cancelText"
    transform-origin="center"
    @close="beforeClose"
    @negative-click="beforeClose"
    @positive-click="sure"
  >
    <template #header>
      <slot name="header" />
    </template>
    <template #icon>
      <slot name="icon" />
    </template>
    <template #default>
      <div class="p-10">
        <slot name="body" />
      </div>
    </template>
    <template #action>
      <slot name="footer" />
    </template>
  </NModal>
</template>
<script lang="ts" setup>
import { setDialogCenter } from '@/layouts/components/hooks/useUser';

type Props = {
  modelValue?: boolean;
  realTitle?: string;
  sureText?: string;
  cancelText?: string;
  isAdd?: boolean;
  isEdit?: boolean;
  isMore?: boolean;
};
const props = withDefaults(defineProps<Props>(), {
  sureText: '确定',
  cancelText: '取消',
});
type Emits = {
  (e: 'sure'): void;
  (e: 'clear'): void;
  (e: 'update:modelValue', v: boolean): void;
};
const emit = defineEmits<Emits>();

const title = computed(() => {
  let str = '新建';
  if (props.isEdit) {
    str = '编辑';
  }
  if (props.isMore) {
    str = '详情';
  }
  return str;
});
const showDialog = computed({
  get: () => props.isAdd || props.isMore || props.isEdit,
  set: (v) => null
});

const sure = () => {
  if (props.isMore) {
    emit('clear');
    return;
  }
  emit('update:modelValue', false);
  emit('sure');
};
const beforeClose = () => {
  if (props.isMore || !props.cancelText) {
    emit('clear');
    emit('update:modelValue', false);
    return;
  }
  window.$alert.warning({
    title: '提示',
    content: '数据未保存，关闭将丢失数据，确认关闭？',
    closable: false,
    'mask-closable': false,
    'positive-text': '确认',
    'negative-text': '取消',
    'onPositiveClick': async () => {
      emit('update:modelValue', false);
      emit('clear');
      return true;
    }
  }).style = setDialogCenter({ top: '20vh' });
};
</script>
